package com.multicampus.simplewiki.ctrl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import com.multicampus.simplewiki.vo.SearchListVO;
import com.multicampus.simplewiki.vo.SearchResultVO;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;

public class RssFeedManager {

	// rss_0.90, rss_0.91, rss_0.92, rss_0.93, rss_0.94, rss_1.0 rss_2.0 or atom_0.3
	private static final String FEED_TYPE = "rss_2.0";
	private static final String TITLE = "SimpleWiki";
	private static final String BASE_URL = "http://localhost:8080/simplewiki";
	private static final String DESCRIPTION = "This is SimpleWiki";
	
    public SyndFeed makeRSS(SearchListVO<SearchResultVO> searchListVO) {
    	SyndFeed feed = new SyndFeedImpl();

    	try {
            feed.setFeedType(FEED_TYPE);

            feed.setTitle(TITLE);
            feed.setLink(BASE_URL);
            feed.setDescription(DESCRIPTION);

            List<SyndEntry> entries = new ArrayList<SyndEntry>();
            SyndEntry entry;
            
            Collection<SearchResultVO> searchResults = searchListVO.getSearchResults();
            Iterator<SearchResultVO> it = searchResults.iterator();
            
            while (it.hasNext()) {
            	entry = makeEntry(it.next());
                entries.add(entry);
            }
            feed.setEntries(entries);

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("ERROR: "+ex.getMessage());
        }
        return feed;
    }
    
    private SyndEntry makeEntry(SearchResultVO doc) {
    	SyndEntry entry = new SyndEntryImpl();
        try {
            entry.setTitle(doc.getTitle());
            entry.setLink(BASE_URL + "/view_page.do?id=" + doc.getId());
            entry.setPublishedDate(doc.getUpdateDate());
            SyndContent description = new SyndContentImpl();
            description.setType("text/plain");
        	description.setValue(doc.getContents());
            entry.setDescription(description);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("ERROR: "+ex.getMessage());
        }
        return entry;
    }
    
}
